<script lang='ts' setup>
import { ElImage, ElIcon } from 'element-plus'
import api from '@/api/api'
import { onMounted, ref } from 'vue'
import { RefreshRight } from '@element-plus/icons-vue'
import { Message } from '@arco-design/web-vue'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus/es'

const wxUrl: string = require('@/assets/wx/wx_qrcode.jpg')
const code = ref('')
const userStore = useUserStore()
let time: NodeJS.Timer
const countdown = ref(0)
// 轮询
function wxIsLogin(): void {
  let params={
    loginCode: code.value
  }
  api.wxIsLogin(params).then(({ data }) => {
    if (data.flag){
      userStore.userInfo = data.data
      sessionStorage.setItem('token', data.data.token)
      userStore.token = data.data.token
      ElMessage({ message: '登录成功', type: 'success' })
      location.reload()
    }
  })
}
const isShow = ref(false)
function getWechatLoginCode(): void {
  api.getWechatLoginCode().then(({ data }) => {
    if (data.flag) {
      Message.success('登陆码获取成功')
      code.value = data.data
      countdown.value = 60
      time = setInterval(() => {
        if (countdown.value > 0) {
          countdown.value--
          // 轮询判断用户是否已经登录
          wxIsLogin()
        } else {
          // 倒计时结束，处理逻辑
          clearInterval(time)
          code.value = '验证码失效，请刷新获取'
          isShow.value=true
        }
      }, 1000)
    } else {
      Message.error('登陆码获取失败')
    }
  })
}

onMounted(async () => {
  await getWechatLoginCode()
})
function getCode():void {
  isShow.value=false
  getWechatLoginCode()
}
</script>
<template>
  <div class='login'>
    <div class='title flex'>
      <span class='text flex'>微信扫码登录</span>
    </div>
    <ElImage class='wx-image' :src='wxUrl'>
      <div slot='error' class='image-slot'>
        加载中<span class='dot'>...</span>
      </div>
    </ElImage>
    <div class='wx-login-info' style='text-align: center;'>
      <p>扫码关注公众号，回复验证码完成登录</p>
      <p>登录验证码：
        <span style='color: red;margin-right: 5px;'>{{ code }}</span>
        <ElIcon @click='getCode' v-show='isShow'>
          <RefreshRight />
        </ElIcon>
      </p>
    </div>
  </div>
</template>
<style lang='scss' scoped>
.login {
  width: 100%;
  background: var(--color-bg-1);
  padding: 0 50px;
  justify-content: space-between;
}

.title {
  width: 100%;
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 5px;
  justify-content: center;

  .text {
    font-size: 24px;
    font-weight: 600;
    color: var(--color-neutral-10);
    line-height: 33px;
    letter-spacing: 2px;
  }
}

.wx-image {
  display: block;
  width: 50%;
  margin: 0 auto;
}

.wx-login-info {
  display: grid;
  gap: 1rem;
}
</style>
